#include <fcntl.h>
#include <sys/sendfile.h>
#include <iostream>

#include <sys/types.h> 
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>

#include <cerrno>
#include <cstring>
#include <cstdlib>

int main()
{
	int fd = open("file", O_RDWR);

        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
                std::cerr << "ERROR opening socket" << std::endl;
                return 1;
        }

        //Creates and initializes sock_addr_in structure.
        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(sockaddr_in));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = INADDR_ANY;
        // htons converts 16bit integer to network byte order.
        int portno = 7171;
        serv_addr.sin_port = htons(portno);

        if(bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "Can't bind socket: errno " << errno << std::endl;
                return 1;
        }
        // Start listening for incoming connections, 5 is size of backlog queue.
        listen(sockfd, 5);

        sockaddr_in cli_addr;
        socklen_t clilen = sizeof(cli_addr);
        int newsockfd = accept(sockfd, (sockaddr*)&cli_addr, &clilen);
        if (newsockfd < 0) {
                std::cerr << "ERROR on accept" << std::endl;
                return 1;
        }
	std::cout << "connected for sending file\n";

	char bufffer[255];
	off_t of;

	int n = read(newsockfd, &of, sizeof(off_t));
	std::cout << of << std::endl;

	int m = read(newsockfd, bufffer, 255);
	std::cout << bufffer << std::endl;
//
//	struct stat stat_buff;
//	fstat(fd,&stat_buff);
//
//	off_t *p = NULL;
//	const int SIZE = 1024;
//	int kkk = sendfile(newsockfd,fd,p,SIZE);
//	while(sendfile(newsockfd,fd,p,SIZE))
//		;;
//	std::cout << "   :sending finished\n";
	close(newsockfd);
	close(sockfd);

	return 0;
}
